<template>
  <div :id="ctlId" v-html="ctlHtml"></div>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch, nextTick } from 'vue';
  import { getCtlHtmlForQuery } from '/@/api/macro/macro';
  import { buildUUID } from '/@/utils/uuid';
  const props = defineProps({
    formCode: {
      type: String,
      required: true,
    },
    fieldName: {
      type: String,
      required: true,
    },
    value: {
      type: String,
      required: false,
      default: '',
    },
  });
  const emits = defineEmits(['update:value']);
  const ctlHtml = ref('');
  const ctlId = ref('');
  onMounted(() => {
    loadCtl();
  });
  watch(
    () => props.fieldName,
    () => {
      loadCtl();
    },
  );
  async function loadCtl() {
    await nextTick();
    if (!props.fieldName) {
      ctlHtml.value = '';
      return;
    }
    const uuid = buildUUID(5);
    ctlId.value = 'ctlBox_' + uuid;
    getCtlHtmlForQuery({ formCode: props.formCode, fieldName: props.fieldName }).then(
      async (res) => {
        let fName = props.fieldName;
        if (fName.startsWith('{$')) {
          fName = fName.substring(2, fName.length - 1);
        }

        let isRadio = false;
        if (res && res.indexOf('radio') != -1) {
          isRadio = true;
        }
        console.log('isRadio', isRadio);
        if (isRadio) {
          // 另外加null，如果只有两个元素，也可以用<>替代
          res += '<input type="radio" name="' + fName + '" value="null"/>未选择';

          ctlHtml.value = res;
          await nextTick();

          // 改名，以免出现重复name，致多组显示规则间的radio相互影响
          $('#' + ctlId.value)
            .find('[name=' + fName + ']')
            .attr('name', fName + '_' + uuid);

          console.log($('input[name=' + fName + ']')[0]);
          $('input[name=' + fName + '_' + uuid + ']').each(function () {
            $(this).click(function () {
              console.log(fName + ' value=', $(this).val());
              emits('update:value', $(this).val());
            });
          });

          // 赋值
          $("input[name='" + fName + '_' + uuid + "'][value=" + props?.value + ']').attr(
            'checked',
            true,
          );
          console.log('props.value', props.value);
          console.log('radio_' + fName, $("input[name='" + fName + "'][checked]").val());
        } else {
          let isCheckbox = false;
          if (res.indexOf('checkbox') != -1) {
            isCheckbox = true;
            res = '<span><input name="' + fName + '" value="1"></span>';
          }

          ctlHtml.value = $('<span>' + res + '</span>')
            .find('[name=' + fName + ']')
            .attr('id', uuid)
            .addClass('ant-input')
            .prop('outerHTML');

          console.log('ctlHtml.value', ctlHtml.value);
          setTimeout(() => {
            const obj = o(uuid);
            obj.onchange = (value) => {
              emits('update:value', obj.value);
            };

            if (!isCheckbox) {
              obj.setAttribute('value', props.value);
            } else {
              emits('update:value', '1');
            }

            if (ctlHtml.value.indexOf('select') != -1 && ctlHtml.value.indexOf('option') != -1) {
              $(`#${uuid}`).val(props?.value);
            }
          });
        }
      },
    );
  }
  function o(s) {
    var e = document.getElementById(s);
    if (e != null) {
      return e;
    }
    e = document.getElementsByName(s);
    if (e.length == 0) {
      return null;
    } else {
      return e[0];
    }
  }
</script>

<style lang="less" scoped>
  :deep(.ctl-item) {
    margin-right: 5px;
  }
  :deep(.ctl-item input[type='radio']) {
    margin-right: 2px;
  }
</style>
